package org.asiainfo.common.flowable.config;

import cn.hutool.core.util.IdUtil;
import org.apache.ibatis.session.SqlSessionFactory;
import org.flowable.engine.ProcessEngineConfiguration;
import org.flowable.spring.SpringProcessEngineConfiguration;
import org.flowable.spring.boot.EngineConfigurationConfigurer;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.transaction.PlatformTransactionManager;

/**
 * 流程引擎配置
 *
 * @author dotor-ww
 */
@AutoConfiguration
public class FlowableConfig implements EngineConfigurationConfigurer<SpringProcessEngineConfiguration> {

    /**
     * 配置引擎
     *
     * @param engineConfiguration 配置类
     */
    @Override
    public void configure(SpringProcessEngineConfiguration engineConfiguration) {
        engineConfiguration.setIdGenerator(() -> IdUtil.getSnowflake().nextIdStr());
    }

    /**
     * 流程引擎配置
     *
     * @param sqlSessionFactory                  工厂
     * @param annotationDrivenTransactionManager 事务
     * @return 配置
     */
    @Bean
    public ProcessEngineConfiguration processEngineConfiguration(SqlSessionFactory sqlSessionFactory,
                                                                 PlatformTransactionManager annotationDrivenTransactionManager) {
        SpringProcessEngineConfiguration processEngineConfiguration = new SpringProcessEngineConfiguration();
        // 指定 MyBatis-Flex  数据源
        processEngineConfiguration.setDataSource(sqlSessionFactory.getConfiguration().getEnvironment().getDataSource());
        // 指定 MyBatis-Flex SQL会话工厂
        processEngineConfiguration.setSqlSessionFactory(sqlSessionFactory);
        // 配置 MyBatis-Flex  的事务管理器
        processEngineConfiguration.setTransactionManager(annotationDrivenTransactionManager);
        return processEngineConfiguration;
    }
}
